﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace N2.Explorer
{
	class IconService: IIconService
	{
		ImageList ImageList;

		void EnsureImageKey(string key, Func<string> defaultImageUrlProvider)
		{
			if (!this.ImageList.Images.ContainsKey(key)) {
				var _imageUrl = VirtualPathUtility.ResolveUrl(defaultImageUrlProvider());

				if (File.Exists(_imageUrl)) {
					
					this.ImageList.Images.Add(
						key,
						Image.FromFile(_imageUrl));
				}
			}
		}

		public void AssignIcons(ContentItem item, TreeNode node)
		{
			var _imageKey = item.GetType().Name;

			this.EnsureImageKey(
				_imageKey,
				() => item.IconUrl
					?? ("~/edit/img/ico/" + (item.IsPage
						? "page.gif"
						: "page_white.gif")));
			
			node.SelectedImageKey = node.ImageKey = _imageKey;
		}

		#region IStudioService Members

		public void Initialize(IStudioForm form)
		{
			this.ImageList = form.ImageList;
		}

		#endregion
	}
}
